const config = require('../config/config')
const { genRandomStr } = require('../utils/tool')
const queryStr = require('querystring');
const crypto = require('crypto');
const qrcode = require('qrcode')
const xmljs = require('xml-js')
const rawbody = require('raw-body');
var contentType = require('content-type')
const { post } = require('../model/http')
const { xml2js } = require('../utils/tool')
const io = require('../utils/socket');
const log = require('../utils/log');

var client = null;
io.on('connection', (curClient) => {
  client = curClient;
})




class Payment {

  _genSign(params) {
    delete params['sign'];

    for (let o in params) {
      if (!params[o]) {
        delete params[o];
      }
    }

    var newObj = Object.keys(params).sort().reduce((obj, key) => {
      obj[key] = params[key];
      return obj;
    }, {})

    let stringA = queryStr.stringify(newObj, null, null, {
      encodeURIComponent: (val) => {
        return queryStr.unescape(val);
      }
    });

    let stringSignTemp = stringA + `&key=${config.key}`

    log.debug(stringSignTemp);

    // 签名
    let sign = crypto.createHash('md5').update(stringSignTemp).digest('hex').toUpperCase();

    return sign;
  }

  //获取二维码
  async getQRcode(ctx) {
    // ctx.body = 'getQRcode'
    //公众账号ID
    let appid = config.appid;
    //商户号
    let mch_id = config.mchid;
    //随机字符串
    let nonce_str = genRandomStr(32).toUpperCase();

    //商品描述
    let body = '一瓶可乐';

    //商户订单号
    let out_trade_no = 'A000000011'

    //标价金额
    let total_fee = 1;

    //终端IP
    let spbill_create_ip = '127.0.0.1'

    //通知地址
    let notify_url = 'http://www.web678.xyz/api/notify'

    //交易类型
    let trade_type = 'NATIVE'


    let params = {
      appid,
      mch_id,
      nonce_str,
      body,
      out_trade_no,
      total_fee,
      spbill_create_ip,
      notify_url,
      trade_type
    }
    // 签名
    let sign = this._genSign(params);
    console.log(sign);

    let json = {
      xml: {
        ...params,
        sign
      }
    }

    let xml = xmljs.json2xml(json, {
      compact: true
    })

    let result = await post(config.url, xml);
    let obj = xml2js(result.data)
    console.log(obj)
    if (obj.return_code === 'SUCCESS') {
      if (obj.err_code === 'ORDERPAID') {
        await ctx.render('paid')
      } else {
        let code = await qrcode.toDataURL(obj.code_url);
        console.log(code)
        await ctx.render('qrcode', {
          code
        })
      }

    }


  }

  //支付结果的通知
  async notify(ctx) {
    let xml = await rawbody(ctx.req, {
      length: ctx.req.headers['content-length'],
      limit: '1mb',
      encoding: contentType.parse(ctx.req).parameters.charset
    })
    log.debug(xml.toString());
    let obj = xml2js(xml)
    let orignSign = obj.sign;
    // console.log(obj)
    log.debug(obj);
    let sign = this._genSign(obj)
    log.debug('orignSign:', orignSign)
    log.debug('mysign:', sign)
    if (sign === orignSign) {
      client.emit('msg', '支付成功')
      ctx.body = `
      <xml>
        <return_code><![CDATA[SUCCESS]]></return_code>
        <return_msg><![CDATA[OK]]></return_msg>
      </xml>
      `
    } else {
      client.emit('msg', '支付失败')
      ctx.body = `
      <xml>
        <return_code><![CDATA[FAIL]]></return_code>
        <return_msg><![CDATA[OK]]></return_msg>
      </xml>
      `
    }
  }

}


module.exports = new Payment()